package com.lottery.job.cqssc;

import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.lottery.common.dto.CqsscDTO;
import com.lottery.common.dto.CqsscResponseDTO;
import com.lottery.common.props.ContextLotteryProperties;
import com.lottery.common.util.Constant;
import com.lottery.common.util.EhCacheUtils;
import com.lottery.common.util.SpringContextHolder;
import com.lottery.cqssc.service.CqsscService;
import com.lottery.job.utils.JobHttpClient;
import com.lottery.web.model.LotteryBettingInfo;
import com.lottery.web.service.LotteryBettingService;

/**
 * 
 * @描述: 重庆时时彩 Job
 *
 * @author LiBing
 * @date 2016年10月21日 下午3:51:23
 *
 */
@Component
public class CqsscScheduledJob extends QuartzJobBean {
	
	private static Logger logger = Logger.getLogger(CqsscScheduledJob.class);
	
	@Autowired
	private ContextLotteryProperties contextProps;
	
	@Override
	protected void executeInternal(JobExecutionContext arg0)
			throws JobExecutionException {
		logger.info("begin to execute CQSSC job.");
		//最新开奖结果
		HashMap<String,String> lastest = new HashMap<String,String>();
		
		//1. 获取job配置信息
		ContextLotteryProperties prop = SpringContextHolder.getBean(ContextLotteryProperties.class);
		CqsscService cs = SpringContextHolder.getBean(CqsscService.class);
		String cqsscURL = prop.getCqsscURL();
		logger.debug("cqsscURL is:"+cqsscURL);
		
		//2. 调用开彩网API,获取开奖结果
		int times = 2;
		String invoker = "CQSSC";
		
		
		boolean isRequestOk = false;
		while(!isRequestOk){
			try {
				CqsscResponseDTO rt = JSON.parseObject(JobHttpClient.sendGetRequest(cqsscURL, times, invoker), CqsscResponseDTO.class);
				//3. 更新缓存
				List<CqsscDTO> data = rt.getData();
				if(data!=null && data.isEmpty()==false){
					for(CqsscDTO cqsscDto:data){
						String expect = cqsscDto.getExpect(); //开奖期数
						String openCode = cqsscDto.getOpencode();//开奖号码
						String openTime = cqsscDto.getOpentime();//开奖时间 
						//String opentimestamp = cqsscDto.getOpentimestamp();//重庆时时彩开奖时间戳
						logger.info("expect:"+expect+", openCode:"+openCode+", openTime:"+openTime);
						try {
							//3.1 判断是否开奖，开奖结果是否计算完成
							String recent = (String)EhCacheUtils.get("cqssc_"+expect);
							if(StringUtils.isBlank(recent)){
								//查询数据库获取最近的开奖结果
								CqsscDTO rs = cs.queryCqssc(cqsscDto);
								if(rs==null || !rs.getExpect().equals(expect)){
									logger.info("cqssc doesn't open:"+expect+",so create it and calculate.");
									//3.2 计算开奖结果
									LotteryBettingService bettingService = SpringContextHolder.getBean(LotteryBettingService.class);
									LotteryBettingInfo bettingInfo = new LotteryBettingInfo();
									bettingInfo.setLotteryPeriods(expect);
									bettingInfo.setLotteryBettingStatus("1");
									bettingInfo.setLotteryType("重庆时时彩");
									List<LotteryBettingInfo> lsBettingInfo = bettingService.queryBettingInfo(bettingInfo);
									boolean isFinish = false;
									for(LotteryBettingInfo info: lsBettingInfo){
										try {
											logger.info("开奖:"+info.getLotteryPeriods()+",购奖号码:"+info.getLotteryBettingCode());
											//[["0","2","3","-","-"],["0","2","4","-","-"],["1","2","3","-","-"],["1","2","4","-","-"]]
											String codeList = info.getLotteryBettingCodeList();
											if(StringUtils.isNotBlank(codeList)){
												codeList = codeList.replace("],[", "#");
												codeList = codeList.replace("[[", "");
												codeList = codeList.replace("]]", "");
												codeList = codeList.replace("\"", "");
												
												String[] codes = codeList.split("#");
												int amcount = 0; //标识当前用户中奖注数
												//循环处理用户是否中奖
												if(codes!=null && codes.length>0){
													for(int k=0;k<codes.length;k++){
														boolean isSuccess = false; //标识当前一组号码是否中奖
														String[] openCodes = openCode.split("\\,");
														String[] tmpcode = codes[k].split("\\,");
														for(int i = 0;i<5;i++){
															if(StringUtils.equals(tmpcode[i], openCodes[i])){
																isSuccess = true;
																continue;
															}else if(!StringUtils.equals(tmpcode[i], "-")){
																isSuccess = false;
																break;
															}
														}
														if(isSuccess){
															amcount++;
														}
													}
													//中奖更新购奖记录中的状态
													if(amcount>0){
														LotteryBettingInfo btInfo = new LotteryBettingInfo();
														btInfo.setLotteryBettingStatus("3");
														btInfo.setLotteryId(info.getLotteryId());
														bettingService.updateLotteryBettingRecord(btInfo);
													}else{
														LotteryBettingInfo btInfo = new LotteryBettingInfo();
														btInfo.setLotteryBettingStatus("4");
														btInfo.setLotteryId(info.getLotteryId());
														bettingService.updateLotteryBettingRecord(btInfo);
													}
												}
											}
											isFinish = true;
										} catch (Exception e) {
											isFinish = false;
											logger.error("开奖失败",e);
										}
									}
									
									if(isFinish || lsBettingInfo==null ||lsBettingInfo.isEmpty()==true){
										//3.3插入开奖结果到重庆时时彩表
										cs.createCqssc(cqsscDto);
										EhCacheUtils.put("cqssc_"+expect,expect);
										//缓存最新开奖结果
										lastest.put("expect",expect);
										lastest.put("openCode", openCode);
										lastest.put(Constant.STATUS, Constant.SECCESS);
										EhCacheUtils.put("cqssc_lastest",JSON.toJSONString(lastest));
									}
								}
							}
						} catch (Exception e) {
							logger.error("CQSSC calculate exception:",e);
						}
					}
				}
				isRequestOk = true;
			} catch (Exception e) {
				logger.error("CQSSC request exception:",e);
			}
		}
	}

}